﻿using CNative.WebApi.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CNative.WebApi.ServiceProcess
{
    public class MyServiceController
    {
        public MyServiceController()
        {
            IsInstallted = IsStarted = false;
        }
        public MyServiceController(string serviceFullName)
        {
            ServiceFullName = serviceFullName;
            //Process = new MyProcess(serviceFullName);
        }
        #region var
        string _ServiceFullName = "";
        /// <summary>
        /// 服务是完整路径
        /// </summary>
        public string ServiceFullName
        {
            get { return _ServiceFullName; }
            set
            {
                _ServiceFullName = value;
                ServiceName = ServiceAPI.GetFileName(ServiceFullName);
                Description = DisplayName = ServiceName;
                RefreshServiceStatus();
            }
        }
        public MyProcess Process { get; set; }
        /// <summary>
        /// 系统用于标志此服务的名称
        /// </summary>
        public string ServiceName { get; set; }

        /// <summary>
        /// 向用户标志服务的友好名称
        /// </summary>
        public string DisplayName { get; set; }
        /// <summary>
        /// 服务的说明
        /// </summary>
        public string Description { get; set; }
        public string 启动类型 { get; set; }
        public string 运行版本 { get; set; }
        public string CPU { get; set; }
        public string 内存 { get; set; }
        /// <summary>
        /// 服务是否已启动
        /// </summary>
        public bool IsStarted { get; set; }
        /// <summary>
        /// 服务是否已安装
        /// </summary>
        public bool IsInstallted { get; set; }

        public string StatusStr { get; set; }

        public string Status
        {
            get
            {
                if (IsInstallted)
                {
                    if (IsStarted)
                        return "已启动";
                    else
                        return "已停止";
                }
                else
                {
                    return "未安装";
                }
            }
        }
        #endregion
        #region 刷新服务状态
        /// <summary>
        /// 刷新服务状态
        /// </summary>  
        public void RefreshServiceStatus()
        {
            try
            {
                内存 = CPU = 运行版本 = "";
                if (ServiceAPI.isServiceIsExisted(ServiceName))
                {
                    int status = ServiceAPI.GetServiceStatus(ServiceName);
                    switch (status)
                    {
                        case 1:
                            StatusStr = "服务未运行";
                            break;
                        case 2:
                            StatusStr = "服务正在启动";
                            break;
                        case 3:
                            StatusStr = "服务正在停止";
                            break;
                        case 4:
                            StatusStr = "服务正在运行";
                            break;
                        case 5:
                            StatusStr = "服务即将继续";
                            break;
                        case 6:
                            StatusStr = "服务即将暂停";
                            break;
                        case 7:
                            StatusStr = "服务已暂停";
                            break;
                        default:
                            StatusStr = "未知状态";
                            break;
                    }
                    if (status == 4 || status == 2 || ServiceHelper.ExistsProcess(ServiceName))
                    {
                        this.IsStarted = true;// "已启动";
                        运行版本 = ServiceHelper.IsWow64Process(ServiceFullName) ? "64位" : "32位";
                        if (Process == null)
                            Process = new MyProcess(ServiceFullName);
                        Process.Refresh();
                        CPU = Process.CPU占用时间;
                        内存 = Process.专用内存;
                    }
                    else
                    {
                        this.IsStarted = false;//"已停止";
                    }
                    this.IsInstallted = true;
                    //2为自动 3为手动 4 为禁用
                    启动类型 = ServiceAPI.GetServiceStartType(ServiceName);
                    if (启动类型 == "2")
                        启动类型 = "自动";
                    else if (启动类型 == "3")
                        启动类型 = "手动";
                    else if (启动类型 == "4")
                        启动类型 = "禁用";
                    else
                        启动类型 = "未知";
                }
                else
                {
                    this.IsInstallted = false;
                    StatusStr = "服务未安装";
                    启动类型 = "";
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.Message);
            }
        }
        #endregion
        #region 安装或卸载服务
        /// <summary>  
        /// 安装或卸载服务  
        /// </summary>  
        /// <param name="serviceName">服务名称</param>  
        /// <param name="btnSet">安装、卸载</param>  
        /// <param name="btnOn">启动、停止</param>  
        /// <param name="txtMsg">提示信息</param>  
        /// <param name="gb">组合框</param>  
        public string InstallOrUninstallServerce()
        {
            string ret = "";
            try
            {
                string location = this.ServiceFullName;
                string Inipath = location.Substring(0, location.LastIndexOf('\\')) + "\\ServiceSetup.ini";
                INIHelper.Write("ServiceName", "ServiceName", ServiceName, Inipath);

                string serviceFileName = this.ServiceFullName;

                if (this.IsInstallted)
                {
                    ServiceAPI.UninstallService(serviceFileName);//.UnInstallmyService(serviceFileName);
                    if (!ServiceAPI.isServiceIsExisted(ServiceName))
                    {
                        ret = "服务【" + ServiceName + "】卸载成功！";
                        RefreshServiceStatus();
                    }
                    else
                    {
                        ret = "服务【" + ServiceName + "】卸载失败，请检查日志！";
                    }
                }
                else
                {
                    ServiceAPI.InstallService(serviceFileName);
                    if (ServiceAPI.isServiceIsExisted(ServiceName))
                    {
                        ret = "服务【" + ServiceName + "】安装成功！";
                        string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(ServiceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(ServiceName) + ")";
                        ret += temp;

                        RefreshServiceStatus();
                    }
                    else
                    {
                        ret = "服务【" + ServiceName + "】安装失败，请检查日志！";
                    }
                }
            }
            catch (Exception ex)
            {
                ret = "error:" + ex;
                LogUtil.Error(ex.Message);
            }
            return ret;
        }
        #endregion
        #region 启动/停止服务
        /// <summary>
        /// 启动/停止服务 
        /// </summary>
        /// <returns></returns> 
        public string SetServerce()
        {
            string ret = "";
            try
            {
                if (this.IsStarted)
                {
                    ServiceAPI.StopService(ServiceName);

                    int status = ServiceAPI.GetServiceStatus(ServiceName);
                    if (status == 1 || status == 3 || status == 6 || status == 7)
                    {
                        ret = "服务【" + ServiceName + "】停止成功！";
                    }
                    else
                    {
                        ret = "服务【" + ServiceName + "】停止失败！";
                    }
                }
                else
                {
                    ServiceAPI.StartService(ServiceName);

                    int status = ServiceAPI.GetServiceStatus(ServiceName);
                    if (status == 2 || status == 4 || status == 5)
                    {
                        ret = "服务【" + ServiceName + "】启动成功！";
                    }
                    else
                    {
                        ret = "服务【" + ServiceName + "】启动失败！";
                    }
                }
                RefreshServiceStatus();
            }
            catch (Exception ex)
            {
                ret = "error:" + ex;
                LogUtil.Error(ex.Message);
            }
            return ret;
        }
        #endregion
        #region 打开所在文件夹
        /// <summary>
        /// 打开所在文件夹
        /// </summary>
        public void OpenFullPath()
        {
            ServiceHelper.OpenFullPath(ServiceFullName);
        }
        #endregion
    }
}
